# file: /data/pyworks/fw_paddleocr_web/app/modules/text_direction.py
from typing import Dict, Any, List
import cv2
import numpy as np
from app.utils.logger import get_logger

logger = get_logger(__name__)


# 文本行方向分类模块
class TextDirectionModule:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(TextDirectionModule, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            logger.info("Initializing TextDirectionModule")
            self._initialized = True

    def classify(self, image_data: bytes, text_regions: List[Dict]) -> Dict[str, Any]:
        """
        分类文本行方向

        Args:
            image_data: 图像字节数据
            text_regions: 文本区域列表

        Returns:
            文本方向分类结果
        """
        try:
            # 将字节数据转换为OpenCV图像
            nparr = np.frombuffer(image_data, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            # 对每个文本区域进行方向分类
            direction_results = []
            for region in text_regions:
                direction = self._classify_text_direction(img, region)
                direction_results.append({
                    "region": region,
                    "direction": direction,
                    "confidence": 0.90
                })

            # 统计主要方向
            main_direction = self._get_main_direction(direction_results)

            return {
                "directions": direction_results,
                "main_direction": main_direction
            }

        except Exception as e:
            raise RuntimeError(f"Text direction classification failed: {str(e)}")

    def _classify_text_direction(self, img, region: Dict) -> str:
        """分类单个文本区域的方向"""
        # 模拟方向分类
        # 可能的方向: "horizontal", "vertical", "slanted"
        return "horizontal"

    def _get_main_direction(self, direction_results: List[Dict]) -> str:
        """获取主要文本方向"""
        # 统计各类方向的数量
        direction_count = {}
        for result in direction_results:
            direction = result["direction"]
            direction_count[direction] = direction_count.get(direction, 0) + 1

        # 返回数量最多的方向
        if direction_count:
            return max(direction_count, key=direction_count.get)
        return "horizontal"
